import Router from 'koa-router';
import proxyService from '../../common/proxyService';
import { downloadCloudToken, getUploadCloudToken } from '../../api/cos';
import upload from '../../utils/multer';
import wxGetMediaId from '../../common/wxGetMediaId';
import { downloadNetSource } from '../../common/dowloadFIle';

const router = new Router();
// 模板详情
router.get('/getDownloadCloudToken', async ctx => {
  const response = await proxyService.postProxy(ctx, downloadCloudToken);
  return (ctx.body = response);
});

router.post('/getUploadCloudToken', async ctx => {
  const response = await proxyService.postProxy(ctx, getUploadCloudToken);
  return (ctx.body = response);
});

//
router.post('/uploadAndGetWxMediaId', upload.single('file'), async ctx => {
  const body = ctx.req.body; // json数据
  let file = ctx.req.file; // 文件对象
  const { url, origin, metarialType, desc, title, ...params } = body;
  if (url) {
    const filePath = await downloadNetSource(url);
    if (filePath.code === 0) {
      return (ctx.body = { ...filePath });
    }
    file = {
      path: filePath,
    };
  }
  // 上传微信
  let resWx = await wxGetMediaId(file.path, metarialType, ctx, { desc, title, ...params }, origin);
  console.log(resWx);
  return (ctx.body = { ...resWx });
});

module.exports = router;
